package su.security.service.impl;

import java.sql.SQLException;
import java.util.List;

import net.kuakao.core.dto.PagerDTO;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;

import su.base.Constants;
import su.security.dao.ISecurityModuleDAO;
import su.security.dao.ISecurityUrlDAO;
import su.security.entity.SecurityModule;
import su.security.entity.SecurityUrl;
import su.security.service.SecurityModuleService;

public class SecurityModuleServiceImpl implements SecurityModuleService {
	@Autowired
	private ISecurityModuleDAO moduleDAO;
	@Autowired
	private ISecurityUrlDAO urlDAO;
	protected final Log log = LogFactory.getLog(getClass());
	//==============
	public List<SecurityModule> queryByPage(PagerDTO s){
		List<SecurityModule> res = null;
		try {
			res = moduleDAO.queryByPage(s);
		} catch (SQLException e) {
			log.error(e.getMessage());
		}
		if(res==null || res.isEmpty())return res;
		for(SecurityModule m : res){
			m.setUrlsStr(this.getStrByUrlids(m.getUrlids()));
		}
		return res;
	}
	public SecurityModule getBaseinfo(int id){
		SecurityModule baseinfo = null;
		try {
			baseinfo = moduleDAO.getBaseinfo(id);
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		return baseinfo;
	}
	public List<SecurityModule> getAllModuleList(){
		List<SecurityModule> res = null;
		try {
			res = moduleDAO.getAllModuleList();
		} catch (SQLException e) {
			log.error(e.getMessage());
		} 
		return res;
	}
	public List<SecurityModule> getModuleList(String ids){
		List<SecurityModule> res = null;
		try {
			res = moduleDAO.getModuleList(ids);
		} catch (SQLException e) {
			log.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 根据url的id字符串取得其对应的url名称的字符串
	 */
	private String getStrByUrlids(String urlids){
		if(StringUtils.isBlank(urlids))return "";
		List<SecurityUrl> list = null;
		try {
			list = urlDAO.getUrlList(urlids);
		} catch (SQLException e) {
			log.error(e.getMessage());
		}
		if(list==null || list.isEmpty())return "";
		String res = "";
		for(SecurityUrl m : list){
			if(StringUtils.isNotBlank(res))res+=",";
			res += m.getUrlname();
		}
		return res;
	}
	//---------------
	public void save(SecurityModule o)throws Exception {
		o.setStatus(Constants.STATUS_ENABLE);
		if(o.getId()==0){
			moduleDAO.insert(o);
		}else{
			moduleDAO.update(o);
		}
	}
	public void remove(int id)throws Exception{
		moduleDAO.remove(id);
	}
}
